package com.woniuxy.school.dietary.order.consumer;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.school.dietary.order.entity.DietOrder;
import com.woniuxy.school.dietary.order.mapper.DietOrderMapper;
import com.woniuxy.school.dietary.order.service.DietOrderService;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;


@Component
public class RabbitMQConsumer {
        @Resource
        private AlipayClient alipayClient;
        @Resource
        private DietOrderService dietOrderService;
        @Resource
        private DietOrderMapper  dietOrderMapper;

/**
 * 延迟队列过期 判断支付状态
 */
@RabbitListener(
        bindings = @QueueBinding(
                value = @Queue("Hell"),
                exchange = @Exchange(value = "order-ex"),
                key = "order"
        )
)
@RabbitHandler
public void process(String OrderNum) throws AlipayApiException {
//        System.out.println("订单支付超时，取消订单");
        //创建交易查询对象
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        HashMap<String, String> map = new HashMap<>();
        map.put("out_trade_no", OrderNum);
        //设置查询参数
        alipayRequest.setBizContent(JSONUtil.toJsonStr(map));
        //发送请求 并返回查询结构
        String body = alipayClient.execute(alipayRequest).getBody();
        //将字符串转json并获取其中alipay_trade_query_response 获得支付详情
        String orderInfo = JSONUtil.parseObj(body).get("alipay_trade_query_response").toString();
        JSONObject obj = JSONUtil.parseObj(orderInfo);
        if(JSONUtil.toJsonStr(obj.get("code")).equals("40004")){
                //订单超时未支付 取消订单
                System.out.println("订单超时未支付 取消订单");
                dietOrderService.cancelOrder(OrderNum);


        }else{
                if(JSONUtil.toJsonStr(obj.get("trade_status")).equals("TRADE_SUCCESS")){
                        //支付成功
                        System.out.println("支付成功");
//                     //判断订单是否已经修改
                        DietOrder order = dietOrderMapper.selectOne(new QueryWrapper<DietOrder>().eq("orderNum", OrderNum));
                        if(order.getState()!=2){
                                dietOrderService.callBack(OrderNum,JSONUtil.toJsonStr(obj.get("send_pay_date")));
                        }
                }else{
                        //发起支付成功 但未支付成功
                        System.out.println("发起支付成功 但未支付成功");
                        dietOrderService.cancelOrder(OrderNum);
                }

        }
}




}
